package org.amos.server.modules.upms.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.base.Throwables;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.amos.core.basic.utils.HttpUtils;
import org.amos.core.basic.vo.R;
import org.amos.filestorage.platform.FilePlatform;
import org.amos.server.modules.upms.service.IFileService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/file")
public class FileController {

    private final IFileService fileService;

    @PostMapping("/upload")
    public R upload(MultipartFile file, String platformId) {
        return R.ok(fileService.uploadFile(file, platformId));
    }

    @PostMapping("/multi-upload")
    public R multiUpload(List<MultipartFile> files, String platformId) {
        return R.ok(Dict.of("url", "UP", "stream-url", ""));
    }

    @GetMapping("/file-stream/{platformId}/**")
    public void getFileContent(HttpServletResponse response, @PathVariable String platformId) {
        String filePath = StrUtil.subAfter(HttpUtils.getURI(), StrUtil.format("/{}/", platformId), false);
        Assert.state(StrUtil.isNotBlank(filePath), "filePath is null");
        FilePlatform filePlatform = fileService.getPlatform(platformId);
        filePlatform.download(filePath, x -> {
            byte[] bytes = IoUtil.readBytes(x);
            if (ArrayUtil.isEmpty(bytes)) {
                response.setStatus(HttpStatus.NOT_FOUND.value());
            }
            try {
                String fileName = StrUtil.subAfter(filePath, "/", true);
                HttpUtils.write(response, fileName, bytes);
            } catch (IOException e) {
                log.error("[file]获取文件流发生异常,异常信息:{}", Throwables.getStackTraceAsString(e));
                response.setStatus(HttpStatus.NOT_FOUND.value());
            }
        });

    }
}
